#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "esp_event.h"
#include "esp_lvgl_port.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include "location_ui.h"
#include "wifi_main.h"
#include "main_ui.h"
#include "md_images.h"
#include "ui_setting.h"
static const char *TAG = "location_ui";

// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);
// 全局变量
static lv_obj_t *location_root;
static lv_obj_t *day_label;
static lv_obj_t *night_label;
static lv_obj_t *alarm_label;
static lv_obj_t *now_label;
static lv_obj_t *date_label;
static lv_obj_t *addr_label;
static bool is_exit_location_ui = false;

// 天气数据结构
typedef struct {
    char day_weather[32];
    char day_temp[8];
    char day_wind_direction[16];
    char day_wind_level[16];
    char night_weather[32];
    char night_temp[8];
    char night_wind_direction[16];
    char night_wind_level[16];
    char current_temp[8];
    char current_humidity[8];
    char current_feels_like[8];
    char alarm_title[64];
    char alarm_level[32];
} weather_data_t;

void exit_location_ui(lv_obj_t *location_root)
{
    if (!location_root) {
        return;
    }

    switch_to_main_screen();   // 切换到主界面
    lv_obj_del(location_root); // 删除UI对象
}

// 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);

        // 保留右划检测
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            lv_obj_t *target = lv_event_get_target(e);
            exit_location_ui(target);
            is_exit_location_ui = true;
        }
    }
}

// HTTP事件处理程序
esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    static char *buffer = NULL;
    static int total_len = 0;

    switch (evt->event_id) {
        case HTTP_EVENT_ON_DATA:
            // 分配缓冲区并接收数据
            if (!buffer) {
                int content_length = esp_http_client_get_content_length(evt->client);
                ESP_LOGI(TAG, "Content length: %d", content_length);
                if (content_length <= 0) {
                    content_length = 1024; // 假设初始大小
                }
                buffer = (char *)malloc(content_length + 1);
                if (!buffer) {
                    ESP_LOGE(TAG, "Failed to allocate buffer");
                    break;
                }
                total_len = 0;
            }
            memcpy(buffer + total_len, evt->data, evt->data_len);
            total_len += evt->data_len;
            buffer[total_len] = '\0';
            break;

        case HTTP_EVENT_ON_FINISH:
            if (buffer) {
                // 解析JSON数据
                cJSON *root = cJSON_Parse(buffer);
                if (root) {
                    weather_data_t weather = { 0 };

                    // 检查响应代码
                    cJSON *code = cJSON_GetObjectItem(root, "code");
                    if (code && cJSON_IsNumber(code) && code->valueint == 200) {
                        // 解析地理位置信息
                        cJSON *sheng = cJSON_GetObjectItem(root, "sheng");
                        cJSON *shi = cJSON_GetObjectItem(root, "shi");
                        if (sheng && cJSON_IsString(sheng) && shi && cJSON_IsString(shi)) {
                            char addr[50] = { 0 };
                            snprintf(addr, sizeof(addr), "%s|%s", sheng->valuestring, shi->valuestring);
                            if (!is_exit_location_ui) {
                                lv_label_set_text(addr_label, addr);
                            }
                        }

                        // 解析白天天气
                        cJSON *weather1 = cJSON_GetObjectItem(root, "weather1");
                        if (weather1 && cJSON_IsString(weather1)) {
                            strncpy(weather.day_weather, weather1->valuestring, sizeof(weather.day_weather) - 1);
                        }

                        cJSON *wd1 = cJSON_GetObjectItem(root, "wd1");
                        if (wd1) {
                            if (cJSON_IsString(wd1)) {
                                strncpy(weather.day_temp, wd1->valuestring, sizeof(weather.day_temp) - 1);
                            } else if (cJSON_IsNumber(wd1)) {
                                snprintf(weather.day_temp, sizeof(weather.day_temp), "%.0f", wd1->valuedouble);
                            }
                        }

                        cJSON *winddirection1 = cJSON_GetObjectItem(root, "winddirection1");
                        if (winddirection1 && cJSON_IsString(winddirection1)) {
                            strncpy(weather.day_wind_direction, winddirection1->valuestring,
                                    sizeof(weather.day_wind_direction) - 1);
                        }

                        cJSON *windleve1 = cJSON_GetObjectItem(root, "windleve1");
                        if (windleve1 && cJSON_IsString(windleve1)) {
                            strncpy(weather.day_wind_level, windleve1->valuestring,
                                    sizeof(weather.day_wind_level) - 1);
                        }

                        // 解析夜间天气
                        cJSON *weather2 = cJSON_GetObjectItem(root, "weather2");
                        if (weather2 && cJSON_IsString(weather2)) {
                            strncpy(weather.night_weather, weather2->valuestring, sizeof(weather.night_weather) - 1);
                        }

                        cJSON *wd2 = cJSON_GetObjectItem(root, "wd2");
                        if (wd2) {
                            if (cJSON_IsString(wd2)) {
                                strncpy(weather.night_temp, wd2->valuestring, sizeof(weather.night_temp) - 1);
                            } else if (cJSON_IsNumber(wd2)) {
                                snprintf(weather.night_temp, sizeof(weather.night_temp), "%.0f", wd2->valuedouble);
                            }
                        }

                        cJSON *winddirection2 = cJSON_GetObjectItem(root, "winddirection2");
                        if (winddirection2 && cJSON_IsString(winddirection2)) {
                            strncpy(weather.night_wind_direction, winddirection2->valuestring,
                                    sizeof(weather.night_wind_direction) - 1);
                        }

                        cJSON *windleve2 = cJSON_GetObjectItem(root, "windleve2");
                        if (windleve2 && cJSON_IsString(windleve2)) {
                            strncpy(weather.night_wind_level, windleve2->valuestring,
                                    sizeof(weather.night_wind_level) - 1);
                        }

                        // 解析当前天气
                        cJSON *nowinfo = cJSON_GetObjectItem(root, "nowinfo");
                        if (nowinfo) {
                            cJSON *temperature = cJSON_GetObjectItem(nowinfo, "temperature");
                            if (temperature) {
                                if (cJSON_IsString(temperature)) {
                                    strncpy(weather.current_temp, temperature->valuestring,
                                            sizeof(weather.current_temp) - 1);
                                } else if (cJSON_IsNumber(temperature)) {
                                    snprintf(weather.current_temp, sizeof(weather.current_temp), "%.1f",
                                             temperature->valuedouble);
                                }
                            }

                            cJSON *humidity = cJSON_GetObjectItem(nowinfo, "humidity");
                            if (humidity) {
                                if (cJSON_IsString(humidity)) {
                                    strncpy(weather.current_humidity, humidity->valuestring,
                                            sizeof(weather.current_humidity) - 1);
                                } else if (cJSON_IsNumber(humidity)) {
                                    snprintf(weather.current_humidity, sizeof(weather.current_humidity), "%.0f%%",
                                             humidity->valuedouble);
                                }
                            }

                            cJSON *feelst = cJSON_GetObjectItem(nowinfo, "feelst");
                            if (feelst) {
                                if (cJSON_IsString(feelst)) {
                                    strncpy(weather.current_feels_like, feelst->valuestring,
                                            sizeof(weather.current_feels_like) - 1);
                                } else if (cJSON_IsNumber(feelst)) {
                                    snprintf(weather.current_feels_like, sizeof(weather.current_feels_like), "%.1f",
                                             feelst->valuedouble);
                                }
                            }
                        }

                        // 解析预警信息
                        cJSON *alarm = cJSON_GetObjectItem(root, "alarm");
                        if (alarm && !cJSON_IsNull(alarm)) {
                            cJSON *title = cJSON_GetObjectItem(alarm, "title");
                            if (title && cJSON_IsString(title)) {
                                strncpy(weather.alarm_title, title->valuestring, sizeof(weather.alarm_title) - 1);
                            }

                            cJSON *signallevel = cJSON_GetObjectItem(alarm, "signallevel");
                            if (signallevel && cJSON_IsString(signallevel)) {
                                strncpy(weather.alarm_level, signallevel->valuestring, sizeof(weather.alarm_level) - 1);
                            }
                        } else {
                            strcpy(weather.alarm_title, "无预警信息");
                        }

                        if (!is_exit_location_ui) {
                            // 更新UI - 使用更简洁的格式
                            lv_label_set_text_fmt(day_label, "白天:%s | %s°C | %s | %s",
                                                  weather.day_weather, weather.day_temp,
                                                  weather.day_wind_direction, weather.day_wind_level);

                            lv_label_set_text_fmt(night_label, "夜间:%s | %s°C | %s | %s",
                                                  weather.night_weather, weather.night_temp,
                                                  weather.night_wind_direction, weather.night_wind_level);

                            lv_label_set_text_fmt(now_label, "当前:%s°C 湿度%s 体感:%s°C",
                                                  weather.current_temp, weather.current_humidity,
                                                  weather.current_feels_like);



                            if (strcmp(weather.alarm_title, "无预警信息") == 0) {
                                lv_label_set_text(alarm_label, weather.alarm_title);
                            } else {
                                lv_label_set_text_fmt(alarm_label, "%s\n%s",
                                                      weather.alarm_title, weather.alarm_level);
                            }
                        }
                    } else {
                        // 处理错误响应
                        cJSON *msg = cJSON_GetObjectItem(root, "msg");
                        if (msg && cJSON_IsString(msg) && !is_exit_location_ui) {
                            lv_label_set_text_fmt(alarm_label, "错误: %s", msg->valuestring);
                        } else if (!is_exit_location_ui) {
                            lv_label_set_text(alarm_label, "获取天气数据失败");
                        }
                    }
                    cJSON_Delete(root);
                }
                free(buffer);
                buffer = NULL;
            }
            break;
        case HTTP_EVENT_ERROR:
            ESP_LOGE("HTTP", "HTTP request error");
            if (buffer) {
                free(buffer);
                buffer = NULL;
            }
            if (!is_exit_location_ui) {
                lv_label_set_text(alarm_label, "获取天气数据失败");
            }
            break;

        default:
            break;
    }
    return ESP_OK;
}

// 获取天气任务
static void refresh_location_task(void *pvParameters)
{
    /*连接wifi*/
    wifi_init();

    // 等待 WiFi 连接成功
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
                                           WIFI_CONNECTED_BIT,
                                           pdFALSE,
                                           pdFALSE,
                                           pdMS_TO_TICKS(30000));
    /*连接失败*/
    if (!(bits & WIFI_CONNECTED_BIT)) {
        if (!is_exit_location_ui) {
            lv_label_set_text(alarm_label, "WiFi连接失败,请先连接网络");
        }
    } else {
        esp_http_client_config_t config = {
            .url = "http://cn.apihz.cn/api/tianqi/tqybip.php?id=88888888&key=88888888",
            .event_handler = http_event_handler,
            .timeout_ms = 10000,
        };

        esp_http_client_handle_t client = esp_http_client_init(&config);
        esp_err_t err = esp_http_client_perform(client);

        if (err != ESP_OK) {
            ESP_LOGE("HTTP", "HTTP request failed: %s", esp_err_to_name(err));
            if (!is_exit_location_ui) {
                lv_label_set_text(alarm_label, "获取天气数据失败");
            }
        }
        vTaskDelay(pdMS_TO_TICKS(1500)); // 延时1.5秒
        if (!is_exit_location_ui) {
            struct tm *timeinfo = get_current_timeinfo();
            char buf[64];
           //strftime(buf, buf_size, VOICE_SD_PATH "/%Y%m%d_%H%M%S.wav", &timeinfo);

            strftime(buf, sizeof(buf), "%Y年%m月%d日", timeinfo);
            lv_label_set_text(date_label, buf);
        }

        esp_http_client_cleanup(client);
    }
    vTaskDelete(NULL);
}

/* 
 * @ brief:创建位置天气UI
*/
lv_obj_t *create_location_ui(void)
{
    is_exit_location_ui = false;
    // 创建根容器（全屏黑色背景）
    location_root = lv_obj_create(NULL);
    if (!location_root) {
        return NULL;
    }
    lv_obj_set_size(location_root, 320, 240);
    lv_obj_set_style_bg_color(location_root, lv_color_hex(get_screen_color_val()), 0);
    lv_obj_add_event_cb(location_root, event_handler, LV_EVENT_GESTURE, NULL);

    // 显示地理位置
    addr_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(addr_label, &myFont, 0);
    lv_obj_set_style_text_color(addr_label, get_btn_font_color(), LV_PART_MAIN);
    lv_label_set_text(addr_label, "获取中...");
    lv_obj_set_size(addr_label, 150, 23);
    lv_obj_align(addr_label, LV_ALIGN_TOP_LEFT, 5, 5);

    // 显示年月日
    date_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(date_label, &myFont, 0);
    lv_obj_set_style_text_color(date_label, get_btn_font_color(), LV_PART_MAIN);
    lv_label_set_text(date_label, "----年--月--日");
    lv_obj_set_size(date_label, 180, 23);
    lv_obj_align(date_label, LV_ALIGN_TOP_RIGHT, -5, 5);

    // 显示分割线
    lv_obj_t *above_bar = lv_bar_create(location_root);
    lv_obj_set_size(above_bar, 310, 2);
    lv_obj_align(above_bar, LV_ALIGN_TOP_MID, 0, 33);
    lv_bar_set_value(above_bar, 100, LV_ANIM_OFF);

    /*白天天气信息*/
    day_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(day_label, &myFont, 0);
    lv_obj_set_style_text_color(day_label, get_btn_font_color(), LV_PART_MAIN);
    lv_label_set_text(day_label, "白天:加载中...");
    lv_obj_set_size(day_label, 310, 30);
    lv_obj_align(day_label, LV_ALIGN_TOP_LEFT, 5, 38);
    lv_label_set_long_mode(day_label, LV_LABEL_LONG_WRAP);

    /*夜间天气信息*/
    night_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(night_label, &myFont, 0);
    lv_obj_set_style_text_color(night_label, get_btn_font_color(), LV_PART_MAIN);
    lv_label_set_text(night_label, "夜间:加载中...");
    lv_obj_set_size(night_label, 310, 30);
    lv_obj_align(night_label, LV_ALIGN_TOP_LEFT, 5, 68);
    lv_label_set_long_mode(night_label, LV_LABEL_LONG_WRAP);

    // 显示分割线
    above_bar = lv_bar_create(location_root);
    lv_obj_set_size(above_bar, 310, 2);
    lv_obj_align(above_bar, LV_ALIGN_TOP_MID, 0, 103);
    lv_bar_set_value(above_bar, 100, LV_ANIM_OFF);

    // 当前天气信息
    now_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(now_label, &myFont, 0);
    lv_obj_set_style_text_color(now_label, get_btn_font_color(), LV_PART_MAIN);
    lv_label_set_text(now_label, "当前:加载中...");
    lv_obj_set_size(now_label, 310, 30);
    lv_obj_align(now_label, LV_ALIGN_TOP_LEFT, 5, 108);
    lv_label_set_long_mode(now_label, LV_LABEL_LONG_WRAP);

    // 显示分割线
    above_bar = lv_bar_create(location_root);
    lv_obj_set_size(above_bar, 310, 2);
    lv_obj_align(above_bar, LV_ALIGN_TOP_MID, 0, 143);
    lv_bar_set_value(above_bar, 100, LV_ANIM_OFF);

    // 预警信息
    alarm_label = lv_label_create(location_root);
    lv_obj_set_style_text_font(alarm_label, &myFont, 0);
    lv_obj_set_style_text_color(alarm_label, lv_color_hex(0xFF0000), LV_PART_MAIN);
    lv_label_set_text(alarm_label, "加载中...");
    lv_obj_set_size(alarm_label, 310, 50);
    lv_obj_align(alarm_label, LV_ALIGN_TOP_LEFT, 5, 145);
    lv_label_set_long_mode(alarm_label, LV_LABEL_LONG_WRAP);

    // 显示太空人 (缩小尺寸以适应小屏幕)
    lv_obj_t *tk_gif = lv_gif_create(location_root);
    lv_gif_set_src(tk_gif, get_gif_data(0));
    lv_obj_set_size(tk_gif, 60, 60);
    lv_obj_align(tk_gif, LV_ALIGN_BOTTOM_RIGHT, -5, -5);

    xTaskCreateWithCaps(refresh_location_task, "refresh_location_task", 4 * 1024, NULL, 5, NULL, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
    return location_root;
}